#!/usr/bin/env python3
# coding: utf-8
# Copyright 2024 Huawei Technologies Co., Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
# ===========================================================================
import os
import json
import tarfile
import platform

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils import common_info, common_utils, venv_installer
from ansible.module_utils.common_info import DeployStatus


class PrometheusInstaller:
    def __init__(self):
        self.module = AnsibleModule(
            argument_spec=dict(
                tags=dict(type="list", required=True),
                resources_dir=dict(type="str", required=True),
                ip_address=dict(type="str", required=True),
                worker_groups=dict(type="list", required=True),
            )
        )
        self.run_tags = self.module.params["tags"]
        self.arch = platform.machine()
        self.resources_dir = os.path.expanduser(self.module.params["resources_dir"])
        self.ip_address = self.module.params["ip_address"]
        self.worker_groups = self.module.params["worker_groups"]
        self.messages = []

    def _module_failed(self):
        return self.module.fail_json(msg="\n".join(self.messages), rc=1, changed=False)

    def _module_success(self):
        return self.module.exit_json(msg="Install prometheus success.", rc=0, changed=True)

    def _find_prometheus_pkg(self, pattern):
        pkgs, msgs = common_utils.find_files(os.path.join(self.resources_dir, "Prometheus*"), pattern)
        self.messages.extend(msgs)
        if not pkgs:
            if "auto" in self.run_tags:
                self.module.exit_json(std_out="can not find prometheus package, prometheus install skipped", rc=0,
                                      result={DeployStatus.DEPLOY_STATUS: DeployStatus.SKIP},
                                      changed=False)
            else:
                self.messages.append("can not find prometheus package.")
                self._module_failed()

        return pkgs[0]
    
    def _get_config(self):
        config_path = self._find_prometheus_pkg("npu_monitor_config.json")
        with open(config_path, 'r') as f:
            data = json.load(f)
            self.config = data.get("prometheus", {})
            self.port = self.config.get("port", 9090)
            self.install_path = self.config.get("install_path", "/opt/prometheus")
            self.npu_exporter_port = data.get("npu_exporter", {}).get("port", 8082)

    def install_pkg(self):
        pkg = self._find_prometheus_pkg("prometheus*{}.tar.gz".format(self.arch))
        if os.path.exists(self.install_path):
            if not os.path.isdir(self.install_path):
                self.messages.append("{} is not dir".format(self.install_path))
                self._module_failed()
        else:
            self.module.run_command(["mkdir", "-p", self.install_path])
        with tarfile.open(pkg, 'r') as tar:
            filenames = tar.getnames()
            tar.extractall(path=self.install_path)
        self.messages.append("install pkg success")
        return os.path.join(self.install_path, filenames[0])
    
    def create_yml(self):
        yml_path = os.path.join(self.install_path, "npu_exporter.yml")
        targets = ["{}:{}".format(worker, self.npu_exporter_port) for worker in self.worker_groups]
        content = [
            "global:",
            " scrape_interval: 15s",
            "scrape_configs:",
            "  - job_name: 'prometheus'",
            "    static_configs:",
            "      - targets: {}".format(str(targets))
        ]
        with open(yml_path, 'w') as f:
            f.write("\n".join(content))
        return yml_path
    
    def create_service(self, software_path, yml_path):
        cmd = [os.path.join(software_path, "prometheus"),
               "--config.file={}".format(yml_path),
               "--web.listen-address={}:{}".format(self.ip_address, self.port)]
        content = [
            "[Unit]",
            "Description=Prometheus Service",
            "After=network.target",
            "[Service]",
            "Type=simple",
            "ExecStart={}".format(" ".join(cmd)),
            "Restart=on-failure",
            "RestartSec=5",
            "[Install]",
            "WantedBy=multi-user.target"
        ]
        with open("/etc/systemd/system/prometheus.service", 'w') as f:
            f.write("\n".join(content))
    
    def setup_service(self):
        self.module.run_command(["systemctl", "enable", "prometheus"])
        self.module.run_command(["systemctl", "start", "prometheus"])

    def run(self):
        try:
            self._get_config()
            software_path = self.install_pkg()
            yml_path = self.create_yml()
            self.create_service(software_path, yml_path)
            self.setup_service()
        except Exception as e:
            self.messages.append(str(e))
            self._module_failed()
        self._module_success()


def main():
    PrometheusInstaller().run()


if __name__ == "__main__":
    main()
